import pandas as pd

def extract_user_features(df: pd.DataFrame) -> pd.DataFrame:
    """
    从事件日志中提取用户级别的行为特征：
    - 浏览次数（view_count）
    - 加购次数（cart_count）
    - 购买次数（buy_count）
    - 活跃天数
    - 首末活跃时间间隔
    """

    print("🔍 提取用户特征...")

    view_counts = df[df['event'] == 'view'].groupby('visitorid').size().rename('view_count')
    cart_counts = df[df['event'] == 'addtocart'].groupby('visitorid').size().rename('cart_count')
    buy_counts  = df[df['event'] == 'transaction'].groupby('visitorid').size().rename('buy_count')

    active_days = df.groupby('visitorid')['date'].nunique().rename('active_days')

    date_range = df.groupby('visitorid')['timestamp'].agg(['min', 'max'])
    date_range['active_span'] = (date_range['max'] - date_range['min']).dt.days

    user_features = pd.concat([view_counts, cart_counts, buy_counts, active_days, date_range['active_span']], axis=1)

    user_features = user_features.fillna(0)

    user_features['cart_rate'] = user_features['cart_count'] / user_features['view_count'].replace(0, 1)
    user_features['buy_rate'] = user_features['buy_count'] / user_features['view_count'].replace(0, 1)

    print(f"✅ 共提取出 {user_features.shape[0]} 个用户特征")
    return user_features.reset_index()
